<?php
namespace common\service;
use common\models\Balance;
use common\models\WithdrawLog;
use common\models\TradeWithdraw;
use common\models\Member;

## 提现
class WithdrawService
{
	
	/*
		配置信息
		b_type
		member_id 
	*/
	public static function conf($params)
	{
		$btype = isset($params['b_type']) ? $params['b_type'] : '';

		if($btype)
		{
			$data = TradeWithdraw::getOne(['b_type' => $btype]);
			if(!$data) return ['state' => false, 'msg' => '请先配置提币规则'];

			unset($data['condition_group']);
			unset($data['condition_rule']);	

			$bInfo = Balance::getBalance($params['member_id'], $btype);
			$data['balance'] = $bInfo['balance'];
			$data['type_name'] = $bInfo['type_name'];
		
		}else
		{
			$data = TradeWithdraw::getAll([]);
			if(!$data) return ['state' => false, 'msg' => '请先配置提币规则'];
			foreach($data as &$val)
			{
				unset($val['condition_group']);
				unset($val['condition_rule']);
				$bInfo = Balance::getBalance($params['member_id'], $val['b_type']);
				$val['balance'] = $bInfo['balance'];
				$val['type_name'] = $bInfo['type_name'];
			}			
		}
		return ['state' => true, 'msg' => 'success', 'data' => $data];
	}


	/*
		提现申请
		* b_type 提现的帐本
		* password 交易密码
		* money  提现的金额
		* type   收款类型 wallet wechat alipay bank
		* address 收款类型为 wallet 是传入 
		* wechat 收款类型为wechat时传入
		* alipay 收款为alipay 时传入
		* bank_info 收款为bank时传入
	*/
	public static function apply($params, $member)
	{
		try{
			$transaction = \Yii::$app->db->beginTransaction();

			## 配置信息
			$conf = TradeWithdraw::getOne(['b_type' => $params['b_type']]);

			$res = self::withdrawCondition($conf, $params, $member);
			if(!$res['state']) return ['state' => false, 'msg' => $res['msg']];

			## 生成日志
			if(!$logId = self::addWithdrawLog($params, $conf,$member)) throw new \Exception("日志添加失败");

			//扣除账本金额
			$res = Balance::reduceBalance($member['member_id'], $params['b_type'], $params['money'], 20, $logId);
			if(!$res['state']) throw new \Exception($res['msg']);

			$transaction->commit();
            return ['state' => false, 'msg' => $res['msg']];
		}catch(\Exception $e)
		{
			$transaction->rollback();
            return ['state' => false, 'msg' =>$e->getMessage()];
		}
	}


	private static function withdrawCondition($conf, $params, $member)
	{
		$money = $params['money'];

		if($money <= 0) return ['state' => false,'msg' => '金额不能小于0'];
		if(!$conf) return ['state'=>false,'msg'=>'配置信息有误'];
		if(!$conf['state']) return ['state'=>false,'msg'=>'暂不能提现'];

		if($conf['min_num'] > 0 && $conf['min_num'] > $money) return ['state' => false, 'msg' => '提现金额不能小于'.$conf['min_num']];
		if($conf['max_num'] > 0 && $conf['max_num'] < $money) return ['state' => false, 'msg' => '提现金额不能大于'.$conf['max_num']];
		if($conf['multiple'] > 0 && $money % $conf['multiple']) return ['state' => false, 'msg' => '提现金额要为'.$conf['multiple'].'的倍数'];

		// $where = ['member_id' => $member['member_id']];
		// $st = mktime(0,0,0,date('m'),date('d'),date('Y'));
		// $num = WithdrawLog::find()->where($where)->andWhere(['>=','create_time',$st])->count();
		// if($num>0) $this->error('每天只能提一笔');
		// if(date("H")<6) $this->error('6点之前不能提现');


		$type = isset($params['type']) ? $params['type'] : 'wallet';
		if($type == 'wallet')
		{
			if(!$params['address']) return ['state' => false, 'msg' => '提币地址不能为空'];
			if(strpos($params['address'],'0x') !== 0) return ['state' => false, 'msg' => '提币地址不正确'];  
			if(strlen($params['address']) != 42) return ['state' => false, 'msg' => '提币地址有误']; 
			$member = Member::find()->where(["address" => $params['address']])->count();
			if($member) return ['state' => false,'msg' => '提币地址不能为本系统生成的']; 	
		}
		return ['state'=>true,'msg'=>'success'];
	}	


	private static  function addWithdrawLog($params, $conf,$member)
	{
		$data = array();
		$data['member_id'] =$member['member_id'];
		$data['money'] = $params['money'];
		$data['b_type'] = $params['b_type'];
		$data['type'] = isset($params['type'])?$params['type']:'wallet';
		$data['state'] = 1;
        if($params['money']>100){
           $fee=round($conf['rate'] * $params['money']/100, 2);
        }else{
            $fee =5;
        }
        if ($fee<=5) {
            $fee=5;
        } 
        
		$data['fee'] = $fee;
		$data['create_time'] = time();
		if($data['type'] == 'wallet') $data['collect_info'] = $params['address'];

		$model = new WithdrawLog;
		if(!$model->load($data,'') || !$model->save()){
			throw new \Exception($model->errors);
			return false;
		} 
		$id = \Yii::$app->db->getLastInsertId();
		return $id;
	}


}